import argparse
import sys
from rich.console import Console
from rich.table import Table
from rich import print as rprint

from taskmanager import TaskManager
from timer import TomatoTimer
from task import Task

__version__ = "0.2.0"


class TomatoClockCLI:
    def __init__(self):
        self.console = Console()
        self.task_manager = TaskManager()

    def add_task(self, name):
        """添加任务"""
        if not name:
            rprint("[red]错误: 任务名称不能为空[/red]")
            return 1

        task_id = self.task_manager.add_task(name)
        rprint(f"[green]✓ 任务添加成功! ID: {task_id}[/green]")
        return 0

    def list_tasks(self):
        """列出所有任务"""
        tasks = self.task_manager.list_tasks()

        if not tasks:
            rprint("[yellow]暂无任务[/yellow]")
            return 0

        table = Table(show_header=True, header_style="bold magenta")
        table.add_column("ID", width=8)
        table.add_column("任务名称")
        table.add_column("完成番茄钟", width=15)
        table.add_column("创建时间", width=20)

        for task in tasks:
            table.add_row(
                str(task.id),
                task.name,
                str(task.completed_pomodoros),
                task.created_at[:16].replace("T", " "),  # 简化时间显示
            )

        self.console.print(table)
        return 0

    def remove_task(self, task_id):
        """删除任务"""
        try:
            task_id_int = int(task_id)
        except ValueError:
            rprint("[red]错误: 任务ID必须是数字[/red]")
            return 1

        if self.task_manager.remove_task(task_id_int):
            rprint(f"[green]✓ 任务 {task_id} 已删除[/green]")
            return 0
        else:
            rprint(f"[red]错误: 未找到ID为 {task_id} 的任务[/red]")
            return 1

    def start_timer(self, task_id, duration):
        """开始番茄钟计时"""
        try:
            task_id_int = int(task_id)
        except ValueError:
            rprint("[red]错误: 任务ID必须是数字[/red]")
            return 1

        task = self.task_manager.get_task(task_id_int)
        if not task:
            rprint(f"[red]错误: 未找到ID为 {task_id} 的任务[/red]")
            return 1

        timer = TomatoTimer(duration_minutes=duration)
        completed = timer.run(task)

        if completed:
            self.task_manager.increment_pomodoro_count(task_id_int)
            # rprint(f"[green]✓ 任务 '{task.name}' 的番茄钟计数已更新[/green]")

        return 0


def main():
    parser = argparse.ArgumentParser(description="番茄时钟命令行工具")

    parser.add_argument("-v", "--version", action="store_true", help="显示版本信息")

    subparsers = parser.add_subparsers(dest="command", help="子命令")

    # add 命令
    add_parser = subparsers.add_parser("add", help="添加新任务")
    add_parser.add_argument("name", help="任务名称")

    # ls 命令
    subparsers.add_parser("ls", help="列出所有任务")

    # rm 命令
    rm_parser = subparsers.add_parser("rm", help="删除任务")
    rm_parser.add_argument("task_id", help="任务ID")

    # start 命令
    start_parser = subparsers.add_parser(
        "start", help="开始番茄钟, -t 可指定时长(分钟)"
    )
    start_parser.add_argument("task_id", help="任务ID")
    start_parser.add_argument(
        "-t", "--time", type=int, default=25, help="番茄钟时长（分钟），默认25分钟"
    )

    args = parser.parse_args()
    cli = TomatoClockCLI()

    if args.version:
        print(__version__)
        return 0

    if args.command == "add":
        return cli.add_task(args.name)
    elif args.command == "ls":
        return cli.list_tasks()
    elif args.command == "rm":
        return cli.remove_task(args.task_id)
    elif args.command == "start":
        return cli.start_timer(args.task_id, args.time)
    else:
        parser.print_help()
        return 0


if __name__ == "__main__":
    sys.exit(main())
